class Solution:
    def minOperations(self, nums1: list, nums2: list) -> int:
        minSum1 = len(nums1)
        minSum2 = len(nums2)
        maxSum1 = minSum1 * 6
        maxSum2 = minSum2 * 6
        sum1 = sum(nums1)
        sum2 = sum(nums2)
        if sum1 == sum2:
            return 0
        if minSum1 > maxSum2 or minSum2 > maxSum1:
            return -1
        left1 = 0
        right1 = len(nums1) - 1
        left2 = 0
        right2 = len(nums2) - 1
        diff = sum1 - sum2
        ops = 0
        nums1.sort()
        nums2.sort()
        while diff != 0:
            # 大于 0 时，要么 nums1 缩小，nums2 增大，小于 0 则反过来
            if diff > 0:
                maxSub = nums1[right1] - 1
                maxAdd = 6 - nums2[left2]
                change = max(maxSub, maxAdd)
                if change == maxSub:
                    right1 -= 1
                else:
                    left2 += 1
                diff -= change
                diff = max(0, diff)
            elif diff < 0:
                maxSub = nums2[right2] - 1
                maxAdd = 6 - nums1[left1]
                change = max(maxSub, maxAdd)
                if change == maxSub:
                    right2 -= 1
                else:
                    left1 += 1
                diff += change
                diff = min(0, diff)
            ops += 1
        return ops
